package com.converters;

import com.domain.WriteData;
import com.enums.Alignment;
import com.enums.TextLevEnum;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class AutoConverter implements Converter{

    /**
     * 数据转换
     * @param key
     * @param obj
     * @return
     */
    public WriteData convertToWriteData(String key, Object obj, Alignment alignment, TextLevEnum levEnum) {
        if (this.checkString(obj)) {
            return DefaultConverters.getConverter(StringConverter.class.getName()).convertToWriteData(key, obj, alignment, levEnum);
        } else {
            return this.checkList(obj) ? DefaultConverters.getConverter(ListConverter.class.getName()).convertToWriteData(key, obj, alignment, levEnum)
                    : DefaultConverters.getConverter(StringConverter.class.getName()).convertToWriteData(key, obj, alignment, levEnum);
        }
    }

    private boolean checkString(Object obj) {
        if (obj == null) {
            return false;
        } else {
            Class<?> clazz = obj.getClass();
            if (clazz.isEnum()) {
                return true;
            } else if (clazz.isPrimitive()) {
                return true;
            } else {
                List<String> basicTypeList = new ArrayList(9);
                Collections.addAll(basicTypeList, new String[]{"java.lang.String", "java.lang.Boolean", "java.lang.Character", "java.lang.Byte", "java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Float", "java.lang.Double"});
                return basicTypeList.contains(clazz.getName());
            }
        }
    }

    private boolean checkList(Object obj) {
        return obj instanceof Iterable;
    }
}
